import mapboxgl from 'mapbox-gl'

import { config } from '@/config'
import { keepTrying } from '@/common'

function getMapStyle(): mapboxgl.Style {
  const mapStyle: mapboxgl.Style = {
    version: 8,
    name: 'mas-map-base-style',
    // sprite: `${config.baseMapPath}/sprites/mas-map-sprite`,
    sprite: `${config.basePath}/sprites/mas-map-sprite`,
    glyphs: `${config.baseMapPath}/fonts/{fontstack}/{range}.pbf`,
    sources: {
      vectorTile: {
        type: 'vector',
        scheme: 'xyz',
        tiles: [`${config.baseMapPath}/layers/vectorTile/{z}/{x}/{y}.mvt`],
        minzoom: 0,
        maxzoom: 6
      },
      countryVectorTile: {
        type: 'vector',
        scheme: 'xyz',
        tiles: [`${config.baseMapPath}/layers/countryVectorTile/{z}/{x}/{y}.mvt`],
        minzoom: 0,
        maxzoom: 6
      }
    },
    layers: [
      {
        id: 'bg',
        type: 'background',
        paint: {
          'background-color': '#202e40'
        }
      },
      {
        id: 'country',
        type: 'fill',
        source: 'countryVectorTile',
        'source-layer': 'country',
        paint: {
          'fill-color': '#404f63',
          'fill-outline-color': '#9e9e9e'
        }
      }
    ]
  }
  return mapStyle
}

export let map: mapboxgl.Map
let mapLoaded = false

export function initMap(containerId: string) {
  if (map) {
    return
  }
  map = new mapboxgl.Map({
    container: containerId,
    style: getMapStyle(),
    center: [108.92361, 34.54083], // for debug
    zoom: 4.0,
    // maxZoom: 16.65
    maxZoom: 16.9
    // maxZoom: 22.5
  })
  map.on('load', () => {
    mapLoaded = true
  })
}

export async function waitForMapLoaded() {
  await keepTrying(() => mapLoaded, 60000)
}
